package com.dzu.medium;

import java.util.*;

/**
 * @author ZhaoDong
 * @date 2022/12/28 10:14
 * @description 150. 逆波兰表达式求值
 */
public class Test150 {
    public static void main(String[] args) {
        System.out.println(evalRPN(new String[]{"2","1","+","3","*"}));
        System.out.println(evalRPN(new String[]{"10","6","9","3","+","-11","*","/","*","17","+","5","+"}));
    }

    public static int evalRPN(String[] tokens) {
        if (tokens.length == 0) {
            return 0;
        }

        List<String> list = Arrays.asList("+", "-", "*", "/");

        Deque<Integer> number = new ArrayDeque<>();

        for (String token : tokens) {
            if (list.contains(token)) {
                if (number.size() < 2) {
                    throw new RuntimeException();
                }

                Integer n2 = number.removeLast();
                Integer n1 = number.removeLast();
                switch (token) {
                    case "+":
                        number.addLast(n1 + n2);
                        break;
                    case "*":
                        number.addLast(n1 * n2);
                        break;
                    case "-":
                        number.addLast(n1 - n2);
                        break;
                    case "/":
                        number.addLast(n1 / n2);
                        break;
                    default:
                        throw new RuntimeException();
                }
            } else {
                number.addLast(Integer.valueOf(token));
            }
        }
        return number.getFirst();
    }

}
